<template>
	<view>
		<uni-card style="font-size: 40rpx;font-weight: bold;" title="温馨提示">
			<view>首次使用，轻松开鞋带！熟悉设备后再根据需要操作使用。</view>
		</uni-card>
		<uni-card>
			<view style="display: flex;">
				<view style="font-size: 40rpx;font-weight: bold;">
					<view style="margin-top: 10rpx;" v-if="list.length>0" v-for="(item,index) in list" :key="index">
						<view>
							<view style="line-height: 30rpx;"><text
									style="font-size: 30rpx;">设备号:{{ item.name }}</text><text v-if="item.power"
									style="margin-left: 10rpx;font-size: 24rpx;">电量:{{ item.power }}%</text></view>
						</view>
					</view>
				</view>
				<view style="flex: 1;text-align: right;padding-top: 30rpx;">
					<button size="mini" type="primary" @click="end()">结束</button>
				</view>
			</view>

		</uni-card>
		<view style="padding: 30rpx;">
			<uni-row class="demo-uni-row">
				<uni-col :span="8">
					<view class="demo-uni-col light">模式</view>
				</uni-col>
				<uni-col :span="8">
					<view class="demo-uni-col light">工作时间</view>
				</uni-col>
				<uni-col :span="8">
					<view class="demo-uni-col light">档位</view>
				</uni-col>
			</uni-row>
			<uni-row class="demo-uni-row">
				<uni-col :span="8">
					<view class="demo-uni-col "> <uni-data-select style="font-size: 40rpx;" :clear="false"
							v-model="modeValue" :localdata="modeRange" @change="modeRangeChange"></uni-data-select>
					</view>
				</uni-col>
				<uni-col :span="8">
					<view class="demo-uni-col ">
						<view class="demo-uni-col "> <uni-data-select :clear="false" v-model="timeValue"
								:localdata="timeRange" @change="timeRangeChange"></uni-data-select></view>
					</view>
				</uni-col>
				<uni-col :span="8">
					<view class="demo-uni-col "><uni-data-select style="font-size: 40rpx;" :clear="false"
							v-model="dangweiValue" :localdata="dangweiRange"
							@change="dangweiRangeChange"></uni-data-select></view>
				</uni-col>
			</uni-row>
		</view>
		<view style="text-align: center;margin-top: 20rpx;">
			<image v-if="modeValue===1" src="/static/images/mode_msg.png" style="width: 300rpx;height: 300rpx;">
			</image>
			<image v-if="modeValue===2" src="/static/images/mode_hit.png" style="width: 300rpx;height: 300rpx;">
			</image>
			<image v-if="modeValue===3" src="/static/images/mode_needle.png" style="width: 300rpx;height: 300rpx;">
			</image>
			<image v-if="modeValue===4" src="/static/images/mode_clash.png" style="width: 300rpx;height: 300rpx;">
			</image>
			<image v-if="modeValue===5" src="/static/images/mode_all.png" style="width: 300rpx;height: 300rpx;">
			</image>
		</view>
		<view style="display: flex;margin-top: 30rpx;">
			<view style="flex: 1;text-align: center;">
				<image src="/static/images/add.png" style="width: 200rpx;height: 200rpx;" @click="add"></image>
			</view>
			<view style="text-align: center;height: 200rpx;line-height: 200rpx;font-size: 40rpx;">{{dangweiIndex}}
			</view>
			<view style="flex: 1;text-align: center;">
				<image src="/static/images/jianshao.png" style="width: 200rpx;height: 200rpx;" @click="jianshao">
				</image>
			</view>
		</view>

	</view>
</template>

<script>
	const mini_cz_obj = uniCloud.importObject('wmz-cz-mini')
	export default {
		data() {
			return {
				list: [],
				tPower: 0,
				modeValue: 1,
				modeRange: [{
						value: 1,
						text: "按摩"
					},
					{
						value: 2,
						text: "捶打"
					},
					{
						value: 3,
						text: "针灸"
					},
					{
						value: 4,
						text: "刮痧"
					},
					{
						value: 5,
						text: "推拿"
					}
				],
				timeValue: 10,
				timeRange: [{
						value: 10,
						text: "十分钟"
					},
					{
						value: 10,
						text: "十五分钟"
					},
					{
						value: 10,
						text: "二十分钟"
					}
				],
				dangweiIndex: 0,
				dangweiValue: 0,
				dangweiRange: [{
						value: 0,
						text: "0档"
					}, {
						value: 1,
						text: "1档"
					},
					{
						value: 2,
						text: "2档"
					},
					{
						value: 3,
						text: "3档"
					},
					{
						value: 4,
						text: "4档"
					},
					{
						value: 5,
						text: "5档"
					},
					{
						value: 6,
						text: "6档"
					},
					{
						value: 7,
						text: "7档"
					},
					{
						value: 8,
						text: "8档"
					},
					{
						value: 9,
						text: "9档"
					},
					{
						value: 10,
						text: "10档"
					},
					{
						value: 11,
						text: "11档"
					},
					{
						value: 12,
						text: "12档"
					},
					{
						value: 13,
						text: "13档"
					},
					{
						value: 14,
						text: "14档"
					},
					{
						value: 15,
						text: "15档"
					}
				],
			}
		},
		async onLoad() {
			let _this = this
			this.list = uni.getStorageSync('wmz-nexmove-cz-bluetooth-data')
			await this.getBLEDeviceServices()
			// await this.readBLECharacteristicValue()
			// await this.starting('25501') //启动
			// await this.mode('ff01020a000500000055') //模式
			// await this.time('55aa030F') //时间
			await this.notifyBLECharacteristicValueChange()
			uni.onBLEConnectionStateChange(function(res) {
				// 该方法回调中可以用于处理连接意外断开等异常情况
				console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`)
			})
			uni.onBLECharacteristicValueChange(function(res) {
				var t = new DataView(e.value);
				console.log("BLE 数值 ====>", e.deviceId, (0, m.ab2hex)(e.value));
				/* console.log(res.value)
				const hexArr = Array.prototype.map.call(
					new Uint8Array(res.value),
					function(bit) {
						return ('00' + bit.toString(16)).slice(-2)
					}
				)
				console.log(hexArr)
				for (var i in hexArr) {
					console.log(parseInt(hexArr[i], 16))
				} */
			})
			setTimeout(() => {
				// this.power('55aa05') //获取电量
			}, 1000);

		},
		methods: {
			async getBLEDeviceServices() {
				let list = this.list
				for (var i in list) {
					if (!list[i].service_id || !list[i].characteristic_id) {
						let deviceId = list[i].device_id
						let bLEDeviceServicesRes = await uni.getBLEDeviceServices({
							deviceId: deviceId
						})
						let o_service_id = bLEDeviceServicesRes.services[0].uuid
						let bLEDeviceCharacteristicsRes = await uni.getBLEDeviceCharacteristics({
							deviceId: deviceId,
							serviceId: o_service_id
						})
						console.log(bLEDeviceCharacteristicsRes)
						let o_characteristic_id = bLEDeviceCharacteristicsRes.characteristics[0].uuid
						let serviceIds = o_service_id.split("-")
						let serviceId = '0000FFF1'
						let characteristicIds = o_characteristic_id.split("-")
						let characteristicId = '0000FFF2'
						let notify_characteristicId = '0000FFF3'

						serviceId = serviceId + "-" + serviceIds[1] + "-" + serviceIds[2] + "-" +
							serviceIds[3] + "-" + serviceIds[4]
						characteristicId = characteristicId + "-" + characteristicIds[1] + "-" +
							characteristicIds[2] + "-" + characteristicIds[3] + "-" + characteristicIds[4]
						notify_characteristicId = notify_characteristicId + "-" + characteristicIds[1] + "-" +
							characteristicIds[2] + "-" + characteristicIds[3] + "-" + characteristicIds[4]
						list[i].service_id = serviceId
						list[i].characteristic_id = characteristicId
						list[i].notify_characteristicId = notify_characteristicId
						this.list = list
						mini_cz_obj.updateBluetooth({
							_id: list[i]._id,
							o_service_id: o_service_id,
							service_id: serviceId,
							characteristic_id: characteristicId,
							o_characteristic_id: o_characteristic_id,
							notify_characteristicId: notify_characteristicId
						})
					}
				}
			},
			//启动
			async starting(valueStr) {
				let list = this.list
				for (var i in list) {
					this.writeBLECharacteristicValue(list[i], valueStr)
				}

			},
			//结束
			async end(valueStr) {
				this.dangweiValue = 0
				let list = this.list
				for (var i in list) {
					this.writeBLECharacteristicValue(list[i], valueStr)
				}
				uni.showToast({
					title: '按摩已结束!',
					icon: 'none'
				})
			},
			//电量
			async power(valueStr) {
				this.tPower = 0
				let list = this.list
				for (var i in list) {
					this.writeBLECharacteristicValue(list[i], valueStr)
				}
			},
			//模式
			async mode(valueStr) {
				this.modeValue = valueStr
				let list = this.list
				for (var i in list) {
					this.writeBLECharacteristicValue(list[i], valueStr)
				}
			},
			//时间
			async time(valueStr) {
				this.timeValue = valueStr
				let list = this.list
				for (var i in list) {
					this.writeBLECharacteristicValue(list[i], valueStr)
				}
			},
			//档位
			async dangwei(valueStr) {
				this.dangweiValue = valueStr
				let list = this.list
				for (var i in list) {
					this.writeBLECharacteristicValue(list[i], valueStr)
				}
			},
			//写数据
			async writeBLECharacteristicValue(item, valueStr) {
				var value = new ArrayBuffer(10),
					n = new DataView(value);
				n.setUint8(0, 255)
				n.setUint8(1, 1)
				n.setUint8(2, this.modeValue)
				n.setUint8(3, this.timeValue)
				n.setUint8(4, 0)
				n.setUint8(5, this.dangweiValue)
				n.setUint8(9, 85)
				console.log("发送数据")
				console.log(item.device_id)
				console.log(item.service_id)
				console.log(item.characteristic_id)
				console.log(this.u(value))
				let res = await uni.writeBLECharacteristicValue({
					deviceId: item.device_id,
					serviceId: item.service_id,
					characteristicId: item.characteristic_id,
					value: value
				})
				console.log(res)
				if (res.errCode !== 0) {
					uni.showToast({
						title: '操作失败!',
						icon: 'error'
					})
				}
			},
			//读数据
			async readBLECharacteristicValue(item, valueStr) {
				let _this = this
				let list = this.list
				for (var i in list) {
					let deviceId = list[i].device_id
					let serviceId = list[i].service_id
					let characteristicId = list[i].characteristic_id
					let res = await uni.readBLECharacteristicValue({
						deviceId: deviceId,
						serviceId: serviceId,
						characteristicId: characteristicId
					})
				}
			},
			u(e) {
				return Array.prototype.map.call(new Uint8Array(e), (function(e) {
					return ("00" + e.toString(16)).slice(-2)
				})).join("")
			},
			M(e) {
				for (var r = [], t = 0; t < e.length / 2; t++) r.push(parseInt(e.substr(2 * t, 2), 16));
				return r
			},
			async notifyBLECharacteristicValueChange() {
				let _this = this
				let list = this.list
				for (var i in list) {
					let deviceId = list[i].device_id
					console.log(deviceId)
					let serviceId = list[i].service_id
					console.log(serviceId)
					let notify_characteristicId = list[i].notify_characteristicId
					console.log(notify_characteristicId)
					uni.notifyBLECharacteristicValueChange({
						deviceId: deviceId,
						serviceId: serviceId,
						characteristicId: notify_characteristicId,
						state: true,
						success: () => {
							// 监听特征值变化
							uni.onBLECharacteristicValueChange((result) => {
								console.log(result)
								const hexData = this.ab2hex(result.value);
								console.log(hexData)
								if (hexData.indexOf('ff50') > -1) {
									console.log("电量:" + hexData.split('ff50')[1].substr(0, 2))
									_this.list[_this.tPower].power = parseInt(hexData.split(
										'ff50')[1].substr(0, 2), 16)
									_this.tPower = _this.tPower * 1 + 1
									if (_this.tPower > 1) {
										_this.tPower = 0
									}
								}

							});
						},
						fail: (err) => {
							console.log(err)
							if (typeof notifyFailCallback === "function") {

							}
						},
					});
				}
			},
			modeRangeChange(e) {
				this.mode(e) //模式
				this.dangweiIndex = 0
				this.dangweiValue = this.dangweiRange[this.dangweiIndex].value
				this.dangwei(this.dangweiValue)
			},
			timeRangeChange(e) {
				this.time(e) //时间
			},
			async dangweiRangeChange(e) {
				this.dangweiIndex = this.dangweiRange.findIndex((item) => item.value === e)
				await this.dangwei('255010102850500000085') //档位
			},
			add() {
				if (this.dangweiIndex < this.dangweiRange.length - 1) {
					this.dangweiIndex = this.dangweiIndex * 1 + 1
					this.dangweiValue = this.dangweiRange[this.dangweiIndex].value
					this.dangwei(this.dangweiValue) //档位
				}

			},
			jianshao() {
				if (this.dangweiIndex > 0) {
					this.dangweiIndex = this.dangweiIndex - 1
					this.dangweiValue = this.dangweiRange[this.dangweiIndex].value
					this.dangwei(this.dangweiValue) //档位
				} else {
					this.dangweiValue = this.dangweiRange[this.dangweiIndex].value
					this.dangwei(this.dangweiValue) //档位
				}
			},
			goBack() {
				// this.end('55aa00') //结束
				uni.navigateBack()
			},
			ab2hex(buffer) {
				const hexArr = Array.prototype.map.call(
					new Uint8Array(buffer),
					function(bit) {
						return ('00' + bit.toString(16)).slice(-2)
					}
				)
				return hexArr.join('')
			}
		},

	}
</script>

<style>
	.demo-uni-row {
		margin-bottom: 10px;
	}

	/* 支付宝小程序没有 demo-uni-row 层级 */
	/* 微信小程序使用了虚拟化节点，没有 demo-uni-row 层级 */
	/* #ifdef MP-ALIPAY || MP-WEIXIN */
	/deep/ .uni-row {
		margin-bottom: 10px;
	}

	/* #endif */

	.demo-uni-col {
		height: 80rpx;
		text-align: center;
		line-height: 80rpx;
		font-size: 40rpx;
	}


	.light {
		background-color: #e5e9f2;
	}
</style>